package com.fatdetection.demo.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fatdetection.demo.bean.Operator;
import com.fatdetection.demo.mapper.OperatorMapper;
import com.fatdetection.demo.mapper.ProjectMapper;
import com.fatdetection.demo.service.OperatorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class OperatorServiceImp implements OperatorService {

    @Autowired
    OperatorMapper operatorMapper;

    @Autowired
    ProjectMapper projectMapper;

    @Override
    public List<Operator> getOptsByProjId(Integer projectId) {
        return operatorMapper.selectList(new QueryWrapper<Operator>()
        .eq("project_id", projectId));
    }

    @Override
    public Page<Operator> selectAllPage(Integer current, Integer size) {
        Page<Operator> page = new Page<>(current, size);
        return operatorMapper.selectPage(page, null);
    }

    @Override
    public int insertOpt(Operator operator) {
        operator.setPassword( DigestUtils.md5DigestAsHex(operator.getPassword().getBytes()));
        if(getOptByUserame(operator.getUsername()) != null){
            return -2;//用户名已存在状态码
        }
        return operatorMapper.insert(operator);
    }

    @Override
    public int editOperator(Operator operator) {
        if(operator.getPassword() != null){
            operator.setPassword( DigestUtils.md5DigestAsHex(operator.getPassword().getBytes()));
        }
        return operatorMapper.update(operator, new UpdateWrapper<Operator>().eq("username", operator.getUsername()));
    }

    @Override
    public int delOperator(String username) {
        return operatorMapper.delete(new QueryWrapper<Operator>().eq("username", username));
    }

    @Override
    public Operator getOptByUserame(String username) {
        return operatorMapper.selectOne(new QueryWrapper<Operator>().eq("username", username));
    }

    @Override
    public List<Operator> findAllByProj(String projectName) {
        return operatorMapper.selectList(new QueryWrapper<Operator>().eq("project_name", projectName));
    }

    @Override
    public List<Operator> findAll() {
        return operatorMapper.selectList(null);
    }

    @Override
    public Operator login(String username,String password) {
        return operatorMapper.selectOne(
                new QueryWrapper<Operator>()
                        .eq("username", username)
                        .eq("password", DigestUtils.md5DigestAsHex(password.getBytes(StandardCharsets.UTF_8))));

    }
}
